import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, Subject, throwError } from 'rxjs';
import { catchError, debounce, debounceTime, tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { ToastService } from './toast.service';
import { mockPre } from 'config';
import { ApiResponse } from '../models/api';

@Injectable({
  providedIn: 'root'
})
export class SystemService {

  constructor(
    private $http: HttpClient,
    private toast: ToastService,
    private router: Router,
  ) { }

  apiPre = `${mockPre}`;
  userInfoObj = null;
  layoutComplete$ = new Subject();

  layoutInitComplete() {
    return new Observable(observer => {
      if (this.layoutComplete$.isStopped) {
        observer.next(this.userInfoObj);
        observer.complete();
      } else {
        this.layoutComplete$.subscribe(res => {
          observer.next(res);
          observer.complete();
        });
      }
    });
  }

  getMenus(): Observable<ApiResponse<any>> {
    return this.$http.get<ApiResponse<any>>(`${this.apiPre}/menu/list`).pipe(
      catchError(err => this.handleError(err, '获取菜单数据失败'))
    );
  }

  isExist(keywords: any): Observable<ApiResponse<any>> {
    return this.$http.get<ApiResponse<any>>(`${this.apiPre}/system/check`, { params: { keywords } }).pipe(
      catchError(err => this.handleError(err, '检查失败'))
    );
  }

  login(params: any): Observable<ApiResponse<any>> {
    return this.$http.post<ApiResponse<any>>(`/api/user/login`, params).pipe(
      catchError(err => this.handleError(err, '登录失败'))
    );
  }

  register(params: any): Observable<ApiResponse<any>> {
    return this.$http.post<ApiResponse<any>>(`/api/user/save`, params).pipe(
      catchError(err => this.handleError(err, '注册失败'))
    );
  }

  userInfo(): Observable<ApiResponse<any>> {
    return this.$http.get<ApiResponse<any>>(`${this.apiPre}/system/userInfo`).pipe(
      tap((res: any) => {
        if (res.success) {
          this.userInfoObj = res.data;
        }
      }),
      catchError(err => {
        let msg = '获取用户信息失败';
        if (`${err.status}` === `403`) {
          msg = '没有权限访问，请登录';
          this.router.navigateByUrl('/auth/login');
        }
        return this.handleError(err, msg);
      })
    );
  }

  private handleError(error: any, title: string, content?: string, param?: any): Observable<any> {
    this.toast.error(title, content, param);
    return throwError(error);
  }
}
